// SPDX-FileCopyrightText: Adam Evyčędo
//
// SPDX-License-Identifier: AGPL-3.0-or-later

package traffic

import (
	"fmt"
	"strconv"
	"strings"
	"time"
)

func parseDepartureTime(departureTime string) (uint, error) {
	hms := strings.Split(departureTime, ":")
	h, err := strconv.ParseInt(hms[0], 10, 0)
	if err != nil {
		return 0, fmt.Errorf("while parsing hour: %w", err)
	}
	m, err := strconv.ParseInt(hms[1], 10, 0)
	if err != nil {
		return 0, fmt.Errorf("while parsing minutes: %w", err)
	}
	s, err := strconv.ParseInt(hms[2], 10, 0)
	if err != nil {
		return 0, fmt.Errorf("while parsing seconds: %w", err)
	}

	return uint(s + m*60 + h*3600), nil
}

func formatDepartureTime(secondsAfterMidnight uint) string {
	h := secondsAfterMidnight / 3600
	ms := secondsAfterMidnight % 3600
	m := ms / 60
	s := ms % 60
	return fmt.Sprintf("%02d:%02d:%02d", h, m, s)
}

func calculateGtfsTime(gtfsTime uint, delay int32, date time.Time,
	timezone *time.Location) time.Time {
	noon := time.Date(date.Year(), date.Month(), date.Day(), 12, 0, 0, 0,
		timezone)
	return noon.Add(time.Duration(-12) * time.Hour).Add(time.Duration(gtfsTime) * time.Second).Add(time.Duration(delay) * time.Second)
}
